from flask import Flask, send_file, jsonify, request
import os
import json
from utils.config import set_sdk_version
from core.BuildAndRun import clone_and_build
from core.ReadExcel import read_libraries_from_excel

# 服务器配置
app = Flask(__name__)
HOST = '0.0.0.0'
PORT = 8888
BUFFER_SIZE = 4096
RESOURCE_DIR = os.path.abspath(os.path.join(os.getcwd(), "Libraries"))

@app.route('/api/match', methods=['POST'])
def match_libraries():
    request_data = request.get_json()
    sdk_version = request_data.get('sdk_version')
    library_keyword = request_data.get('library_keyword')
    selected_indices = request_data.get('selected_indices', [])
    
    # 设置SDK版本
    set_sdk_version(sdk_version)
    
    # 从Excel读取库信息
    libraries, _, _ = read_libraries_from_excel()
    
    # 模糊匹配库名
    matched_libraries = []
    for lib in libraries:
        lib_name = lib['name'] if isinstance(lib, dict) and 'name' in lib else lib
        if isinstance(lib_name, str) and library_keyword.lower() in lib_name.lower():
            matched_libraries.append(lib)
    
    # 根据选择的索引获取库
    if selected_indices:
        selected_libraries = [matched_libraries[i] for i in selected_indices if 0 <= i < len(matched_libraries)]
    else:
        selected_libraries = matched_libraries
    
    # 返回匹配结果
    matched_names = [lib['name'] if isinstance(lib, dict) and 'name' in lib else lib for lib in matched_libraries]
    return jsonify({
        'status': 'matched',
        'matched_libraries': matched_names,
        'count': len(matched_libraries)
    })

@app.route('/api/build', methods=['POST'])
def build_har_files():
    request_data = request.get_json()
    selected_libraries = request_data.get('selected_libraries', [])
    
    result_files = []
    for lib in selected_libraries:
        try:
            # 执行构建
            lib_name = lib.get('name', str(lib)) if isinstance(lib, dict) else str(lib)
            print(f"开始构建库: {lib_name}")
            
            # 构建库
            clone_and_build(lib)
            
            # 查找生成的HAR文件
            har_files = []
            for root, dirs, files in os.walk(RESOURCE_DIR):
                for file in files:
                    if file.endswith(".har"):
                        # 返回完整路径
                        har_files.append(os.path.join(root, file))
            
            # 添加到结果列表
            result_files.extend(har_files)
            
            # 返回进度更新
            return jsonify({
                'status': 'completed',
                'library': lib_name,
                'message': f"库 {lib_name} 构建完成",
                'har_files': [f for f in har_files],
                'count': len(har_files)
            })

        except Exception as e:
            lib_name = str(lib)
            return jsonify({
                'status': 'error',
                'library': lib_name,
                'message': f"构建出错: {str(e)}"
            })
    
    # 返回最终结果
    if result_files:
        return jsonify({
            'status': 'completed',
            'har_files': [f for f in result_files],
            'count': len(result_files)
        })
    else:
        return jsonify({
            'status': 'error',
            'message': '未生成任何HAR文件'
        })

@app.route('/download/<filename>', methods=['GET'])
def download_file(filename):
    file_path = os.path.join(RESOURCE_DIR, filename)
    if not os.path.exists(file_path):
        return "File not found", 404
    
    # 参考resource.md中的方法，将文件传输到设备沙箱目录
    try:
        # 1. 读取文件内容
        with open(file_path, 'rb') as f:
            file_data = f.read()
        
        # 2. 获取沙箱目录路径
        dest_dir = os.path.join(os.path.dirname(file_path), 'sandbox')
        os.makedirs(dest_dir, exist_ok=True)
        
        # 3. 写入沙箱目录
        dest_path = os.path.join(dest_dir, filename)
        with open(dest_path, 'wb') as f:
            f.write(file_data)
        
        # 4. 校验文件完整性
        if os.path.getsize(dest_path) != os.path.getsize(file_path):
            os.remove(dest_path)
            return "文件传输失败", 500
        
        print(f"文件已成功传输到沙箱目录: {dest_path}")
        return send_file(file_path, as_attachment=True)
    except Exception as e:
        return f"文件传输错误: {str(e)}", 500

if __name__ == "__main__":
    app.run(host=HOST, port=PORT, debug=True)